package com.xmy.cultivate.service.impl;

import com.aliyun.oss.common.utils.StringUtils;
import com.xmy.cultivate.schedule.MyJob;
import com.xmy.cultivate.service.QuartzService;
import lombok.SneakyThrows;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;


@Service
public class QuartzServiceIpml implements QuartzService {
    @Autowired
    private Scheduler scheduler;
    private final String JOB_NAME_PREFIX = "JOB_"; // 任务名称前缀
    @SneakyThrows
    private void scheduleJob(Class<? extends Job> jobClass, String groupName, String jobName, Map<String, Object> params, Trigger trigger) {
        jobName = StringUtils.join(JOB_NAME_PREFIX, jobName);
        // 创建任务
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, groupName).build();

        // 添加参数
        jobDetail.getJobDataMap().putAll(params);
        // 将触发器与任务绑定到调度器内
        scheduler.scheduleJob(jobDetail, trigger);
    }
    @SneakyThrows
    public void addJobWithCron(Class<? extends Job> jobClass, String jobName, String cronExpression, Map<String, Object> params) {
        // 使用job类名作为组名
        String groupName = jobClass.getSimpleName();

        // 基于表达式构建触发器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
        CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobName, groupName).withSchedule(cronScheduleBuilder).build();

        // 将触发器与任务绑定到调度器内
        this.scheduleJob(jobClass, groupName, jobName, params, cronTrigger);
    }



    /**
     * 生成定时推送时间
     * @param startDate
     * @param endDate
     * @param pushTime
     * @throws SchedulerException
     */
    public void setSchedulDailyJob(String id,LocalDate startDate, LocalDate endDate, String pushTime) throws SchedulerException {
        if (startDate == null || endDate == null || startDate.isAfter(endDate)){
            throw new IllegalArgumentException("Invalid start or end date");
        }

        // 确保调度器已经启动
        if (!scheduler.isStarted()) {
            scheduler.start();
        }
        // 解析推送时间
        String[] timeParts = pushTime.split(":");
        int hour = Integer.parseInt(timeParts[0]);
        int minute = Integer.parseInt(timeParts[1]);
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)){
            // 动态生成任务名和组名
            String jobName = "myJob_" + UUID.randomUUID().toString();
            String groupName = "group1_" + UUID.randomUUID().toString();
            // 构建 Cron 表达式
            String cronExpression = String.format("0 %d %d ? * *", minute, hour);


            // 创建 JobDetail 实例
            JobDetail job = JobBuilder.newJob(MyJob.class)
                    .withIdentity(jobName, groupName)
                    .usingJobData("id", id)
                    .usingJobData("pushTime", pushTime)
                    .build();
            // 创建 Trigger 实例，并设置开始和结束时间
            Date startTime = Date.from(date.atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toInstant());
            Date endTime = Date.from(date.atStartOfDay().plusDays(1).atZone(java.time.ZoneId.systemDefault()).toInstant());
            // 创建 Trigger 实例
            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(jobName + "_" + date.toString()+'_'+pushTime, groupName)
                    .startAt(startTime)
                    .endAt(endTime)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                    .build();
            try {
                // 检查 Job 是否已经存在
                if (scheduler.checkExists(new JobKey(jobName, groupName))) {
                    // 如果 Job 已经存在，可以选择更新现有的 Job
                    scheduler.rescheduleJob(new TriggerKey(trigger.getKey().getName(), trigger.getKey().getGroup()), trigger);
                } else {
                    // 调度 Job
                    scheduler.scheduleJob(job, trigger);
                    System.err.println("Job scheduled successfully: " + jobName + " on " + date + " at " + pushTime);
                }

            } catch (SchedulerException e) {
                System.err.println("Failed to schedule job: " + e.getMessage());
                throw e;
            }
        }
    }


    /**
     * 获取所有任务
     * @throws SchedulerException
     */
    public void listScheduledJobs() throws SchedulerException {
        // 获取所有组名
        List<String> groupNames = scheduler.getJobGroupNames();
        for (String groupName : groupNames) {
            // 获取组内的所有 JobKey
            Set<JobKey> jobKeys = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName));
            for (JobKey jobKey : jobKeys) {
                System.out.println("Job Key: " + jobKey.getName() + ", Group: " + jobKey.getGroup());
                // 获取与 JobKey 关联的所有 TriggerKey
                List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
                for (Trigger trigger : triggers) {
                    System.out.println("  Trigger Key: " + trigger.getKey().getName() + ", Group: " + trigger.getKey().getGroup());
                    System.out.println("  Cron Expression: " + ((CronTrigger) trigger).getCronExpression());
                    System.out.println("  Next Fire Time: " + trigger.getNextFireTime());
                    System.out.println("  Previous Fire Time: " + trigger.getPreviousFireTime());
                    System.out.println("  Start Time: " + trigger.getStartTime());
                    System.out.println("  End Time: " + trigger.getEndTime());
                }
            }
        }
    }



    /**
     * 删除
     * @param jobName
     * @param groupName
     * @throws SchedulerException
     */
    public void deleteJob(String jobName, String groupName) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, groupName);
        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
            System.err.println("Job deleted successfully: " + jobName + " in group " + groupName);
        } else {
            System.err.println("Job not found: " + jobName + " in group " + groupName);
        }
    }

    /**
     * 暂停
     * @param jobName
     * @param groupName
     * @throws SchedulerException
     */
    public void pauseJob(String jobName, String groupName) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, groupName);
        if (scheduler.checkExists(jobKey)) {
            scheduler.pauseJob(jobKey);
            System.err.println("Job paused successfully: " + jobName + " in group " + groupName);
        } else {
            System.err.println("Job not found: " + jobName + " in group " + groupName);
        }
    }

    /**
     * 恢复
     * @param jobName
     * @param groupName
     * @throws SchedulerException
     */
    public void resumeJob(String jobName, String groupName) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, groupName);
        if (scheduler.checkExists(jobKey)) {
            scheduler.resumeJob(jobKey);
            System.err.println("Job resumed successfully: " + jobName + " in group " + groupName);
        } else {
            System.err.println("Job not found: " + jobName + " in group " + groupName);
        }
    }



}
